package com.example.demo.controller;

import com.example.demo.model.AuctionRecord;
import com.example.demo.model.UserInfo;
import com.example.demo.service.AuctionService;
import com.example.demo.service.OrderService;
import com.example.demo.util.ConstVariable;
import com.example.demo.config.AjaxResult;
import com.example.demo.model.AuctionInfo;
import com.example.demo.vo.AuctionVO;
import com.example.demo.model.OrderInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.math.BigDecimal;

@RestController
@RequestMapping("/auction")
@Slf4j
public class AuctionController {
    
    @Autowired
    private AuctionService auctionService;
    
    @Autowired
    private OrderService orderService;
    
    @GetMapping("/list")
    public AjaxResult list() {
        try {
            List<AuctionVO> auctions = auctionService.getAuctionList();
            log.info("获取拍卖列表成功，数量: {}", auctions.size());
            
            // 打印每个拍卖商品的详细信息
            auctions.forEach(auction -> {
                log.info("拍卖商品信息: id={}, 商品名称={}, 当前价格={}, 原价={}, 图片={}, 状态={}, 地址={}",
                    auction.getId(),
                    auction.getProductName(),
                    auction.getCurrentPrice(),
                    auction.getOriginalPrice(),
                    auction.getFirstImage(),
                    auction.getStatus(),
                    auction.getLocation()
                );
            });
            
            return AjaxResult.success(auctions);
        } catch (Exception e) {
            log.error("获取拍卖列表失败", e);
            return AjaxResult.fail("获取拍卖列表失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        return AjaxResult.success(auctionService.getAuctionById(id));
    }
    
    @PostMapping("/bid")
    public AjaxResult bid(@RequestBody AuctionRecord record, HttpSession session) {
        log.info("收到出价请求: auctionId={}, bidPrice={}", record.getAuctionId(), record.getBidPrice());
        
        // 从 session 获取当前用户ID，如果没有则返回错误
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        if (userInfo == null) {
            return AjaxResult.fail("请先登录");
        }
        
        // 设置用户ID到记录中
        record.setUserId(userInfo.getId().longValue());
        
        return auctionService.placeBid(
            record.getAuctionId(), 
            record.getUserId(), 
            record.getBidPrice()
        );
    }
    
    @GetMapping("/records/{auctionId}")
    public AjaxResult getRecords(@PathVariable Long auctionId) {
        return AjaxResult.success(auctionService.getAuctionRecords(auctionId));
    }

    // 生成订单号
    private String generateOrderNo() {
        Date now = new Date();
        return String.format("PM%tY%tm%td%tH%tM%tS%03d",
                now, now, now, now, now, now,
                (int) (Math.random() * 1000));
    }

    @PostMapping("/end/{auctionId}")
    public AjaxResult endAuction(@PathVariable Long auctionId) {
        try {
            // 获取拍卖信息
            AuctionInfo auction = auctionService.getAuctionById(auctionId);
            if (auction == null) {
                return AjaxResult.fail("拍卖信息不存在");
            }

            // 检查是否有人竞拍
            if (auction.getWinnerId() == null) {
                return AjaxResult.fail("没有人参与竞拍");
            }

            // 准备订单数据
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setOrderNo(generateOrderNo());
            orderInfo.setProductId(auction.getProductId().intValue());
            orderInfo.setSellerId(Integer.parseInt(auction.getSellerId()));
            orderInfo.setBuyerId(auction.getWinnerId().intValue());
            orderInfo.setTotalPrice(auction.getCurrentPrice().toPlainString());
            
            // 获取买家默认地址
            Long defaultAddressId = auctionService.getDefaultAddress(auction.getWinnerId());
            if (defaultAddressId == null) {
                return AjaxResult.fail("买家未设置默认收货地址");
            }
            orderInfo.setReceivingId(defaultAddressId.intValue());

            // 创建订单
            log.info("创建拍卖订单，订单信息：{}", orderInfo);
            OrderInfo createdOrder = orderService.createOrderWithDetails(orderInfo);
            if (createdOrder == null) {
                return AjaxResult.fail("创建订单失败");
            }

            // 更新拍卖状态
            auction.setStatus(2); // 已结束
            boolean updated = auctionService.update(auction);
            if (!updated) {
                log.warn("更新拍卖状态失败：auctionId={}", auctionId);
            }

            log.info("拍卖结束，创建订单成功：auctionId={}, orderNo={}, winner={}, price={}",
                    auctionId, orderInfo.getOrderNo(), auction.getWinnerId(), auction.getCurrentPrice());

            return AjaxResult.success(createdOrder);
        } catch (Exception e) {
            log.error("拍卖结束创建订单失败", e);
            return AjaxResult.fail("创建订单失败: " + e.getMessage());
        }
    }
} 